window.addEvent('domready', function(){
	var form = $('frmSearch');
	
	//pagination
	new Pagination($('pagination'),{
		onPageChange: function(obj){
			form.offset.value = obj.getPageNumber()-1;
			search_cont(form);
		}
	});	
	
	//table header untuk sorting
	new SortableTableHeader($('jbt_table').getElement('tr[class:header]'), {tableFieldName:['jbt_id','jbt_nama', 'dep_nama', 'jbt_level'],
		onHeaderClick:function(item, fieldName, sort){
			form.orderby.value = fieldName+" "+sort;
			search_cont(form);
		}
	});
	
	search(form);
});

function search(form){
	form.set('send',{
		onSuccess: function(res){
			//table content
			var json = JSON.decode(res);
			$('jbt_table_content').set('html', json.table_content);
			
			//rubah jumlah halamannya
			$('pagination').retrieve('pagination').setPageCount(Math.ceil(json.table_num_record/10));
		}
	}).send();
}

function search_cont(form){
	form.set('send',{
		onSuccess: function(res){
			//table content
			var json = JSON.decode(res);
			$('jbt_table_content').set('html', json.table_content);
		}
	}).send();
}

function do_add(){
	FBModal_show2(APP.base+'/ajax/addModal', 'post', "", true, true, null, {
		onSuccess: function(){
			new FormCheck('frmModal',{submitByAjax:true, 
		        onAjaxSuccess: function(res){
					var json = JSON.decode(res);
					FBModal_message(APP.base+'/ajax/messageDialog', "Save", json.msg);
					search($('frmSearch'));
		        }
		    });
		}
	});
}

function do_delete(rowElement, id){
	ajax(APP.base+'/ajax/delete/'+id, "post", "", $empty, function(res){
		var json = JSON.decode(res);
		if (!json.error){
			//tween opacity and destroy it
			rowElement.get('tween').chain(function(){
				rowElement.destroy();
			}).start('opacity',[1,0]);
		}
		FBModal_message(APP.base+'/ajax/messageDialog', "Delete", json.msg);
		search($('frmSearch'));
	});
}

function do_edit(dep_id){
	FBModal_show2(APP.base+'/ajax/editModal/'+dep_id, 'post', "", true, true, null, {
		onSuccess: function(){
			new FormCheck('frmModal',{submitByAjax:true, 
		        onAjaxSuccess: function(res){
					var json = JSON.decode(res);
					FBModal_message(APP.base+'/ajax/messageDialog', "Save", json.msg);
					search($('frmSearch'));
		        }
		    });
		}
	});
}

var idCheck =  {
		request: null,
		error: false,
		msg:''
	};

function checkID(el){
	var error = false;
	if (idCheck.request==null){
		idCheck.request = new Request({
			method: 'post', 
			async:false,
			onSuccess: function(responseText) {
				var json = JSON.decode(responseText)
				if (json.error){
					idCheck.msg = json.msg;
				}
				idCheck.error = json.error;
			}
		});
	}
	idCheck.request.options.url = APP.base+'/ajax/validateID/'+el.value;
	idCheck.request.send('');
	if (idCheck.error) el.errors.push(idCheck.msg);
	return !idCheck.error;
}